<template>
  <view class="container" style="padding-top: 1rpx;">
    
    <!-- 表单内容 -->
    <view class="form-container" >
		<view class="form-item">
			<view class="item-label">用户id：</view>{{userInfo.id}}
		</view>
      <!-- 头像上传 -->
      <view class="form-item avatar-item">
        <view class="item-label">头像</view>
        <view class="avatar-wrapper">
          <!-- 方式一：使用button的chooseAvatar开放能力 -->
          <button 
            class="avatar-btn wx-avatar-btn" 
            open-type="chooseAvatar" 
            @chooseavatar="handleChooseAvatar"
          >
            <image 
              :src="userInfo.avatar " 
              mode="aspectFill" 
              class="avatar"
            ></image>
          </button>
          
          <!-- 方式二：使用uni.chooseImage + uni.uploadFile -->
          <button 
            class="avatar-btn uni-avatar-btn" 
            @click="chooseImage"
          >
            <image 
              :src="userInfo.avatar " 
              mode="aspectFill" 
              class="avatar"
            ></image>
          </button>
          
          <view class="change-avatar">
            <text class="iconfont icon-camera"></text>
            <text>更换头像</text>
          </view>
        </view>
      </view>
      
      <!-- 上传进度条 -->
      <view class="upload-progress" v-if="uploading">
        <view class="progress-bar" :style="{ width: progress + '%' }"></view>
        <text class="progress-text">{{ progress }}%</text>
      </view>
      
      <!-- 昵称 -->
      <view class="form-item">
        <view class="item-label">昵称</view>
        <view class="item-input">
          <input 
            type="nickname"
            v-model="userInfo.nickname" 
            placeholder="请输入昵称" 
            maxlength="12"
            @blur="validateNickname"
          />
          <view class="clear-btn" @click="clearNickname" v-if="userInfo.nickname">
            <text class="iconfont icon-close"></text>
          </view>
        </view>
      </view>
      
      
      
    
    </view>
    <button class="save-btn" @click="saveProfile">
      <text>保存</text>
    </button>
    <!-- 底部提示 -->
    <view class="footer-tip">
      <text>注：修改个人资料后，可能需要重新登录才能生效</text>
    </view>
    
    <!-- 加载中 -->
    <view class="loading-mask" v-if="isLoading">
      <view class="loading-icon">
        <text class="iconfont icon-loading"></text>
      </view>
    </view>
    
    <!-- 操作结果提示 -->
    <view class="toast" :class="{ show: toast.show }">
      <text>{{ toast.message }}</text>
    </view>
  </view>
</template>

<script>
	import {
		request
	} from '@/utils/request.js'

export default {
  data() {
    return {
      userInfo: {
        avatar: '',
        nickname: '',
        gender: 2, // 0-男，1-女，2-保密
        phone: '',
        signature: ''
      },
      defaultAvatar: '/static/images/default-avatar.png',
      isLoading: false,
      formErrors: {
        nickname: '',
        signature: ''
      },
      toast: {
        show: false,
        message: ''
      },
      // 图片上传相关
      tempFilePaths: [],
      uploading: false,
      progress: 0,
      // 显示哪种上传方式（默认显示微信官方方式）
      showWxAvatarBtn: true,
      showUniAvatarBtn: false
    };
  },
  
  onLoad() {
    this.getUserInfo();
  },
  
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        this.isLoading = true;
        const res = await request({
          url: 'user/center',
          method: 'GET'
        });
			
       if(res.status==200){
       						this.userInfo = res.data
       					} else {
          this.showToast(res.message || '获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
        this.showToast('网络请求失败');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 处理微信官方头像选择
    handleChooseAvatar(e) {
      const avatarUrl = e.detail.avatarUrl;
      this.showToast('正在上传头像...');
      
      // 使用uni.uploadFile上传微信头像
      this.uploadAvatar(avatarUrl);
    },
    
    // 选择图片（自定义方式）
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.tempFilePaths = res.tempFilePaths;
          this.uploadAvatar(res.tempFilePaths[0]);
        },
        fail: (err) => {
          console.error('选择图片失败', err);
          this.showToast('选择图片失败');
        }
      });
    },
    
    // 上传头像
    uploadAvatar(filePath) {
      this.uploading = true;
      this.progress = 0;
      
      const uploadTask = uni.uploadFile({
        url: 'https://apishop.aa.ka.dajunzhu.cn/v1/login/upload', // 替换为你的上传接口地址
        filePath: filePath,
        name: 'img',
        formData: {
          userId: this.userInfo.userId || ''
        },
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              const data = JSON.parse(res.data);
			  console.log(data)
              if (data.status === 200) {
                this.userInfo.avatar = data.data.url;
                this.showToast('头像上传成功');
              } else {
                this.showToast(res.message || '头像上传失败');
              }
            } catch (e) {
              console.error('解析上传结果失败', e);
              this.showToast('头像上传失败');
            }
          } else {
            this.showToast('头像上传失败，状态码：' + res.statusCode);
          }
        },
        fail: (err) => {
          console.error('上传头像失败', err);
          this.showToast('头像上传失败');
        },
        complete: () => {
          this.uploading = false;
          this.progress = 0;
        }
      });
      
      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        this.progress = res.progress;
        console.log('上传进度：' + res.progress);
        console.log('已经上传的数据长度：' + res.totalBytesSent);
        console.log('预期需要上传的数据总长度：' + res.totalBytesExpectedToSend);
      });
    },
    
    // 验证昵称
    validateNickname() {
      if (!this.userInfo.nickname.trim()) {
        this.formErrors.nickname = '昵称不能为空';
        return false;
      }
      this.formErrors.nickname = '';
      return true;
    },
    
    
    // 清除昵称
    clearNickname() {
      this.userInfo.nickname = '';
    },
    
    
    
    // 保存个人资料
    async saveProfile() {
      // 表单验证
      if (!this.validateNickname() ) {
        return;
      }
      
      try {
        this.isLoading = true;
        const res = await request({
          url: 'user/up-info',
          method: 'POST',
          data: {
            nickname: this.userInfo.nickname,
            avatar: this.userInfo.avatar
          }
        });
        
        if (res.status === 200) {
          this.showToast('资料更新成功');
          setTimeout(() => {
            this.navigateBack();
          }, 1500);
        } else {
          this.showToast(res.message || '资料更新失败');
        }
      } catch (error) {
        console.error('保存资料失败', error);
        this.showToast('网络请求失败');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },
    
    // 显示提示
    showToast(message) {
      this.toast.message = message;
      this.toast.show = true;
      
      setTimeout(() => {
        this.toast.show = false;
      }, 2000);
    }
  }
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}
.save-btn{
	width: 300rpx;
	border-radius: 40rpx;
	height: 80rpx;
	background-color: #e74c3c;
	color: #fff;
	margin-top: 30rpx;
}
// 导航栏
.nav-bar {
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #eeeeee;
  
  .back-btn,
  .save-btn {
    width: 80rpx;
    text-align: center;
    color: #333333;
    font-size: 32rpx;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: 500;
  }
}

// 表单容器
.form-container {
  background-color: #ffffff;
  
  .form-item {
    padding: 30rpx;
    border-bottom: 1rpx solid #eeeeee;
    
    .item-label {
      font-size: 32rpx;
      color: #666666;
      margin-bottom: 20rpx;
    }
    
    .item-input {
      position: relative;
      
      input {
        height: 80rpx;
        font-size: 32rpx;
        color: #333333;
      }
      
      textarea {
        min-height: 120rpx;
        font-size: 32rpx;
        color: #333333;
      }
      
      .clear-btn {
        position: absolute;
        right: 0;
        top: 20rpx;
        width: 40rpx;
        height: 40rpx;
        text-align: center;
        color: #999999;
      }
      
      .word-count {
        position: absolute;
        right: 0;
        bottom: 10rpx;
        font-size: 24rpx;
        color: #999999;
      }
    }
    
    .item-value {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      text {
        font-size: 32rpx;
        color: #333333;
      }
      
      .edit-btn {
        color: #409EFF;
        font-size: 30rpx;
      }
    }
  }
  
  // 头像项
  .avatar-item {
    .avatar-wrapper {
      position: relative;
      width: 160rpx;
      height: 160rpx;
      
      // 微信官方头像按钮
      .wx-avatar-btn {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        background-color: transparent;
        border: none;
        overflow: hidden;
        z-index: 10;
      }
      
      // 自定义头像按钮
      .uni-avatar-btn {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        background-color: transparent;
        border: none;
        overflow: hidden;
        z-index: 5;
      }
      
      .avatar {
        width: 100%;
        height: 100%;
      }
      
      .change-avatar {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 50rpx;
        line-height: 50rpx;
        text-align: center;
        background-color: rgba(0, 0, 0, 0.5);
        color: #ffffff;
        font-size: 24rpx;
        z-index: 20;
        
        .iconfont {
          margin-right: 5rpx;
        }
      }
    }
  }
  
  // 上传进度条
  .upload-progress {
    position: relative;
    height: 10rpx;
    background-color: #f0f0f0;
    margin: 20rpx 30rpx;
    border-radius: 5rpx;
    
    .progress-bar {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      background-color: #409EFF;
      border-radius: 5rpx;
      transition: width 0.3s ease;
    }
    
    .progress-text {
      position: absolute;
      top: -30rpx;
      right: 0;
      font-size: 24rpx;
      color: #409EFF;
    }
  }
  
  // 性别项
  .gender-item {
    .gender-options {
      display: flex;
      align-items: center;
      
      .gender-option {
        width: 180rpx;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        border: 1rpx solid #eeeeee;
        border-radius: 40rpx;
        margin-right: 20rpx;
        font-size: 32rpx;
        color: #666666;
        
        .icon-check {
          margin-left: 10rpx;
          color: #409EFF;
        }
      }
      
      .gender-option.active {
        border-color: #409EFF;
        color: #409EFF;
      }
    }
  }
}

// 底部提示
.footer-tip {
  padding: 30rpx;
  font-size: 24rpx;
  color: #999999;
  text-align: center;
}

// 加载中
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .loading-icon {
    width: 160rpx;
    height: 160rpx;
    border-radius: 16rpx;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      color: #ffffff;
      font-size: 60rpx;
      animation: rotate 1.5s linear infinite;
    }
  }
}

// 提示框
.toast {
  position: fixed;
  bottom: 200rpx;
  left: 50%;
  transform: translateX(-50%);
  padding: 20rpx 40rpx;
  background-color: rgba(0, 0, 0, 0.7);
  color: #ffffff;
  border-radius: 10rpx;
  font-size: 32rpx;
  opacity: 0;
  transition: opacity 0.3s ease;
  
  &.show {
    opacity: 1;
  }
}

// 旋转动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
